package Tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 迭代
 */
public class PreorderTraversalIteration {
    public static List<Integer> solution(TreeNode node){
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while(!stack.isEmpty() || node != null){
            while (node != null){
                res.add(node.val);
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            node = node.right;
        }
        return res;
    }

    public static void main(String[] args) {

        TreeNode left1 = new TreeNode(4);
        TreeNode left2 = new TreeNode(5);
        TreeNode right1 = new TreeNode(6);

        TreeNode left = new TreeNode(2,left1,left2);
        TreeNode right = new TreeNode(3,null,right1);
        TreeNode node = new TreeNode(1,left,right);

        List<Integer> list = solution(node);
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
}
